<template>
	<view>
		<view v-if="toReg" class="user-login-page">
			<view class="header-container">
				<image class="header-bg" src="/static/h5/image/userLogin/login_head.png"></image>
			</view>

			<view class="main-container">
				<view class="user-info">
					<view class="user-info-title">手机号</view>
					<view class="user-info-content">
						<input class="user-info-input" maxlength="11" type="number" @input="phoneInput" id="user_phone"
							placeholder="请输入手机号码" />
					</view>
				</view>
				<view v-if="!wechatUser" class="user-info">
					<view class="user-info-title">用户昵称</view>
					<view class="user-info-content">
						<input class="user-info-input" type="text" @input="nameInput" id="user_name"
							placeholder="请输入用户昵称" />
					</view>
				</view>
				<view class="user-info">
					<view class="user-info-title">验证码</view>
					<view class="user-info-content">
						<input class="user-info-input" maxlength="6" type="number" @input="codeInput"
							placeholder="请输入验证码" />
						<text class="btn-code">验证码</text>
					</view>
				</view>
				<button class="btn login-btn" @click="reg()">登录</button>
			</view>

			<view class="footer-container">
				<image class="footer-bg" src="/static/image/common/foot.png"></image>
			</view>
		</view>
		<view v-else></view>
	</view>
</template>

<script>
	var app = getApp()
	//#ifdef H5  
	import $ from '@/static/h5/js/jquery-1.9.1.min.js';
	import gt from '@/static/h5/js/gt.js'
	//#endif
	import {
		baseUrl
	} from '@/utils/constant.js'
	import {
		http
	} from '@/utils/commonRequest.js';

	export default {
		data() {
			return {
				phoneNum: '',
				userName: '',
				code: '',
				wechatUser: null,
				params: {},
				toReg: false,
				inviterId: '',
				inviteActId: ''
			}
		},
		mounted() {},
		onLoad(options) {
			let code = options.code,
				appid = options.appid;
			this.inviteActId = options.inviteActId || ''
			this.inviterId = options.inviterId || ''
			uni.showLoading({
				title: "加载中"
			})
			console.log(options)
			let params = {
				code: code,
				appid: appid
			}
			let that = this
			let returnUrl = decodeURIComponent(uni.getStorageSync("returnUrl"))
			that.returnUrl = returnUrl
			http
				.get('/auth/getAuthInfo', {
					params: params
				})
				.then(res => {
					res = res.data
					if (200 == res.code) {
						uni.hideLoading()
						if ("LOGIN" == res.state) {
							uni.setStorageSync("memberInfo", res.memberInfo)
							uni.setStorageSync("jwt", res.jwt)						
							uni.switchTab({
								url: returnUrl,
								fail() {
									uni.redirectTo({
										url: returnUrl,
										fail() {
											uni.switchTab({
												url: "/pages/my/my"
											})
										}
									})
								}
							})
						} else if("TO_REG" == res.state) {
							that.toReg = true
							that.wechatUser = res.wechatUser
						}
					} else {
						uni.hideLoading()
						that.toReg = true
					}
					that.initCodeTime()
					that.initGeetest()
				})
				.catch(err => {
					uni.hideLoading()
					uni.showModal({
						content: "查询用户信息失败，请稍后再试",
						showCancel: false,
						success:function(){
							uni.switchTab({
								url: "/pages/index/index"
							})
						}
					})
					console.log('局部test 获取用户列表 get fail----');
					console.log(err);
				});
		},
		methods: {
			phoneInput: function(e) {
				this.phoneNum = e.target.value
			},
			nameInput: function(e) {
				this.userName = e.target.value
			},
			codeInput: function(e) {
				this.code = e.target.value
			},
			initCodeTime: function() {
				$.ajax({
					type: "get",
					url: baseUrl + "/index/seconds",
					dataType: "json",
					success: function(R) {
						let data = JSON.parse(R.msg);
						if (data.seconds > 0) {
							let i = data.seconds;
							let a = setInterval(function() {
								i--;
								if (i == 0) {
									$(".btn-code").text("验证码");
									clearInterval(a);
								} else {
									$(".btn-code").text(i + " S");
								}
							}, 1000);
						} else {
							$(".btn-code").text("验证码");
						}
					},
					error: function(R) {
						alert(R.msg);
					}
				});
			},

			initGeetest: function() {
				let that = this
				let handler = function(captchaObj) {
					captchaObj.onSuccess(function() {
						let phone = that.phoneNum;
						let result = captchaObj.getValidate();
						if (!result) {
							uni.showToast({
								title: "请完成验证",
								icon: "none"
							})
							return;
						}
						$.ajax({
							url: baseUrl + '/index/sendCodeByGeetest',
							type: 'POST',
							dataType: 'json',
							data: {
								phone: phone,
								geetest_challenge: result.geetest_challenge,
								geetest_validate: result.geetest_validate,
								geetest_seccode: result.geetest_seccode
							},
							success: function(R) {
								if (R.code == 200) {
									let txt = $(".btn-code").text();
									if (txt == "验证码") {
										$(".btn-code").text(" S");
									}
									let i = 60;
									let a = setInterval(function() {
										i--;
										if (i == 0) {
											$(".btn-code").text("验证码");
											clearInterval(a);
										} else {
											$(".btn-code").text(i + " S");
										}
									}, 1000);
								}
							}
						});
					});
					$(".btn-code").click(function() {
						let phone = that.phoneNum;
						if (phone == "") {
							uni.showToast({
								title: "请输入手机号码",
								icon: "none"
							});
							return;
						}
						if (!(/^1[123456789]\d{9}$/.test(phone))) { //验证手机号
							uni.showToast({
								title: "输入手机号有误",
								icon: "none"
							});
							return;
						}
						let txt = $(this).text();
						if (txt == "验证码") {
							captchaObj.verify();
						}
					});
				}
				$.ajax({
					url: baseUrl + "/index/validateCodeGT?t=" + (new Date()).getTime(),
					type: "get",
					dataType: "json",
					success: function(data) {
						initGeetest({
							// 以下配置参数来自服务端 SDK
							gt: data.gt,
							challenge: data.challenge,
							offline: !data.success, // 表示用户后台检测极验服务器是否宕机
							new_captcha: data.new_captcha, // 用于宕机时表示是新验证码的宕机
							product: "bind", // 产品形式，包括：float，popup
							width: "300px",
							https: true
						}, handler)
					}
				})
			},

			reg: function() {
				var that = this
				console.log("开始注册")
				var user_phone = this.phoneNum;
				var user_code = this.code;
				if (user_phone == "") {
					uni.showToast({
						title: "请输入手机号码",
						icon: "none"
					})
					return;
				}
				if (!(/^1[123456789]\d{9}$/.test(user_phone))) { //验证手机号
					uni.showToast({
						title: "输入手机号有误",
						icon: "none"
					})
					return;
				}
				if (!that.wechatUser && !that.userName) {
					uni.showToast({
						title: "请输入用户昵称",
						icon: "none"
					})
					return;
				}
				if (user_code == "") {
					uni.showToast({
						title: "请输入验证码",
						icon: "none"
					})
					return;
				}
				uni.showLoading({
					title: "登录中"
				})
				console.log("wechatuser:", that.wechatUser)
				var params = null
				if (that.wechatUser) {
					params = {
						user_logo: that.wechatUser.image,
						user_name: encodeURIComponent(that.wechatUser.name),
						user_gender: that.wechatUser.sex,
						user_phone: user_phone,
						user_code: user_code,
						inviterId: that.inviterId,
						inviteActId: that.inviteActId
					}
				} else {
					params = {
						user_logo: baseUrl + '/attached/image/00000000/head.png',
						user_name: encodeURIComponent(that.userName),
						user_gender: '1',
						user_phone: user_phone,
						user_code: user_code,
						inviterId: that.inviterId,
						inviteActId: that.inviteActId
					}
				}
				$.ajax({
					type: "get",
					url: baseUrl + "/index/regUser2",
					data: params,
					dataType: "json",
					xhrFields: {
						withCredentials: true
					},
					success: function(R) {
						uni.hideLoading()
						if (R.msg == "SUCCESS") {
							var ua = window.navigator.userAgent.toLowerCase();
							if (ua.match(/micromessenger/i) == 'micromessenger') {
								uni.redirectTo({
									url: '/pages/yxlm/yxlm?returnUrl=' + encodeURIComponent(that.returnUrl)
								})
							} else {
								uni.switchTab({
									url: that.returnUrl,
									fail() {
										uni.redirectTo({
											url: that.returnUrl,
											fail() {
												uni.switchTab({
													url: "/pages/my/my"
												})
											}
										})
									}
								})
							}
						} else if (R.msg == "NULL") {
							uni.showToast({
								title: "请先获取验证码",
								icon: "none"
							});
						} else if (R.msg == "WRONG_CODE") {
							uni.showToast({
								title: "验证码错误！",
								icon: "none"
							});
						} else if (R.msg == "WRONG_PHONE") {
							uni.showToast({
								title: "登录手机号需和接收验证码手机号相同！",
								icon: "none"
							});
						} else if (R.msg == "SAME_PHONE") {
							uni.showToast({
								title: "该手机号码已被使用！",
								icon: "none"
							});
						} else if (R.msg == "SAME_USER") {
							let backUrl = that.returnUrl ? that.returnUrl : '/pages/index/index'
							uni.redirectTo({
								url: backUrl
							})
						}
					}
				})
			}
		}
	}
</script>

<style>
	.user-login-page {
		display: flex;
		flex-direction: column;
		min-height: 100vh;
	}

	.header-container {
		position: relative;
		width: 100%;
		height: 420rpx;
	}

	.header-bg {
		width: 100%;
		height: 100%;
	}

	.main-container {
		flex: 1;
		position: relative;
		top: 30rpx;
		margin: 0 auto;
		padding: 30rpx 50rpx;
		width: 700rpx;
		border-radius: 10rpx;
		background-color: #fff;
	}

	.user-info {
		position: relative;
		margin-bottom: 20rpx;
		line-height: 80rpx;
		font-size: 30rpx;
	}

	.user-info-title {
		color: #5f5f5f;
		font-weight: bold;
	}

	.user-info-content {
		display: flex;
		align-items: center;
		height: 80rpx;
		border-bottom: 1px solid #dedede;
	}

	.user-info-input {
		flex: 1;
	}

	.btn-code {
		margin-left: 30rpx;
		width: 150rpx;
		line-height: 50rpx;
		text-align: center;
		color: #5674fa;
		border: 1px solid #5674fa;
		border-radius: 25rpx;
	}

	.btn {
		display: block;
		width: 600rpx;
		border-radius: 40rpx;
		margin: 50rpx auto 0;
		line-height: 80rpx;
		font-size: 30rpx;
		border: none;
		outline: none;
	}

	.login-btn {
		color: #fff;
		background-color: #5674fa;
	}

	.reg-btn {
		color: #5674fa;
		background-color: #efefef;
	}

	.footer-container {
		width: 100%;
		height: 150rpx;
		margin-top: 120rpx;
	}

	.footer-bg {
		width: 100%;
		height: 100%;
	}
</style>
